package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.pojo.Spec;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    ElasticsearchTemplate elasticsearchTemplate;

    @Override
    public Map search(Map<String, String> searchMap) {
        Map<String, Object> resultMap = new HashMap<>();
        if (searchMap != null) {
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();

            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            if (!StringUtils.isEmpty(searchMap.get("keywords"))) {
                MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", searchMap.get("keywords"));
                boolQueryBuilder.must(matchQueryBuilder);
            }
            if (StringUtils.isNotEmpty(searchMap.get("brand"))) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("brandName", searchMap.get("brand")));
            }
            if(StringUtils.isNotEmpty(searchMap.get("price"))){
                String[] prices = searchMap.get("price").split("-");
                //500-1000
                if(prices.length==2){
                    boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(prices[0]).lte(prices[1]));
                }
                boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(prices[0]));
            }
            Set<String> keySet = searchMap.keySet();
            for (String key : keySet) {
                if (key.startsWith("spec_")) {
                    String value = searchMap.get(key).replace("%2B", "+");
                    boolQueryBuilder.filter(QueryBuilders.matchQuery("specMap." + key.substring(5) + ".keyword", value));
                }
            }
            nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
            //按照品牌聚合
            String skuBrand = "skuBrand";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName").size(18));
            //按照规格聚合
            String skuSpec = "skuSpec";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));
            String pageNum = searchMap.get("pageNum");
            String pageSize = searchMap.get("pageSize");
            if (StringUtils.isEmpty(searchMap.get("pageNum"))) {
                pageNum = "1";
            }
            if (StringUtils.isEmpty(searchMap.get("pageSize"))) {
                pageSize = "30";
            }
            nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum) - 1, Integer.parseInt(pageSize)));
            if (StringUtils.isNotEmpty(searchMap.get("sortField")) && StringUtils.isNotEmpty(searchMap.get("sortRule"))) {
                if (searchMap.get("sortRule").equals("ASC")) {
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(searchMap.get("sortField")).order(SortOrder.ASC));
                } else {
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(searchMap.get("sortField")).order(SortOrder.DESC));
                }
            }
            HighlightBuilder.Field field = new HighlightBuilder.Field("name")
                    .preTags("<span style='color:red'>")
                    .postTags("</span>");
            nativeSearchQueryBuilder.withHighlightFields(field);
            AggregatedPage<SkuInfo> resultInfo = elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), SkuInfo.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    List<T> list = new ArrayList<>();
                    SearchHits hits = searchResponse.getHits();
                    for (SearchHit hit : hits) {
                        String sourceAsString = hit.getSourceAsString();
                        SkuInfo skuInfo = JSON.parseObject(sourceAsString, SkuInfo.class);
                        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                        if (highlightFields != null && highlightFields.size() > 0) {
                            Text[] names = highlightFields.get("name").getFragments();
                            StringBuilder sb = new StringBuilder();
                            for (Text name : names) {
                                sb.append(name);
                            }
                            skuInfo.setName(sb.toString());
                        }
                        list.add((T) skuInfo);
                    }

                    return new AggregatedPageImpl<>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
                }
            });
            resultMap.put("total", resultInfo.getTotalElements());
            resultMap.put("PageTotal", resultInfo.getPageable());
            resultMap.put("rows", resultInfo.getContent());
            //封装品牌分组结果
            StringTerms brandTerms = (StringTerms) resultInfo.getAggregation(skuBrand);
            List<String> brandList = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("brandList", brandList);
            StringTerms specTerms = (StringTerms) resultInfo.getAggregation(skuSpec);
            List<String> specList = specTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("specList", formartSpec(specList));
            resultMap.put("pageNum", pageNum);
        }
        return resultMap;
    }

    public Map<String, Set<String>> formartSpec(List<String> specList) {
        Map<String, Set<String>> result = new HashMap<>();
        for (String specJsonString : specList) {
            Map<String, String> specMap = JSON.parseObject(specJsonString, Map.class);
            Set<String> keySet = specMap.keySet();
            for (String specKey : keySet) {
                String specValue = specMap.get(specKey);
                Set<String> specValueSet = result.get(specKey);
                if (specValueSet == null) {
                    specValueSet = new HashSet<>();
                }
                specValueSet.add(specValue);
                result.put(specKey, specValueSet);
            }
        }
        return result;
    }
}
